package cn.com.checne.controller.superManager;

import cn.com.checne.constants.Constants;
import cn.com.checne.constants.LogConstants;
import cn.com.checne.constants.NavigateConstants;
import cn.com.checne.controller.BaseController;
import cn.com.checne.dao.BusinessCategoryDao;
import cn.com.checne.dao.BusinessInfoDao;
import cn.com.checne.dao.LogInfoDao;
import cn.com.checne.model.domain.BusinessCategory;
import cn.com.checne.model.domain.BusinessInfo;
import cn.com.checne.model.domain.UserInfo;
import cn.com.checne.model.dto.BusinessQuery;
import cn.com.checne.util.PageBean;
import cn.com.checne.util.StringTools;
import cn.com.checne.util.TimeUtils;
import cn.com.checne.util.WebUtils;
import cn.com.checne.util.images.ImageContentUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value="/super/business")
public class BusinessInfoManagerController extends BaseController{
	protected static final Logger logger = Logger.getLogger(BusinessInfoManagerController.class);

	@Resource
	private BusinessCategoryDao cateDao;
	@Resource
	private BusinessInfoDao businessDao;
	@Resource
	private LogInfoDao logDao;
	
	//业务领域--首页
	@RequestMapping(value="/index.do")
	public String index(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws Exception {
		return "super/frame/frame_business";
	}
	
	//业务领域--左侧导航
	@RequestMapping(value="/left.do")
	public String left(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws Exception {
		return "super/business/left";
	}
	
	//业务领域--列举所有的栏目
	@RequestMapping(value="/category-list.do")
	public ModelAndView categoryList(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws Exception {
		ModelAndView mav = new ModelAndView();
		int languageId = (String)request.getSession().getAttribute(Constants.SESSIONLANGUAGE) != null ? Integer.parseInt((String)request.getSession().getAttribute(Constants.SESSIONLANGUAGE)) : 1 ;
		List<BusinessCategory> cateList = cateDao.getAll(languageId);
		modelMap.put("cateList", cateList);
		modelMap.put("languageId", languageId);
		mav.setViewName("super/business/category-list");
		mav.addAllObjects(modelMap);
		return mav ;
	}
	
	//业务领域--栏目新增、修改页面
	@RequestMapping(value="/category-show.do")
	public ModelAndView categoryShow(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws Exception {
		ModelAndView mav = new ModelAndView();
		int cateId = WebUtils.getRequestParameterAsInt(request, "cateId", 0);
		int languageId = (String)request.getSession().getAttribute(Constants.SESSIONLANGUAGE) != null ? Integer.parseInt((String)request.getSession().getAttribute(Constants.SESSIONLANGUAGE)) : 1 ;
		BusinessCategory cate = new BusinessCategory();
		cate.setLanguageId(languageId);
		String opt = "create" ;
		if(cateId > 0){
			cate = cateDao.getBusinessCategory(cateId);
			opt = "update" ;
		}
		modelMap.put("cate", cate);
		modelMap.put("opt", opt);
		mav.setViewName("super/business/category-show");
		mav.addAllObjects(modelMap);
		return mav ;
	}
	
	//业务领域--栏目新增
	@RequestMapping(value="/category-create.do")
	public ModelAndView categoryCreate(HttpServletRequest request,HttpServletResponse response,HttpSession session, ModelMap modelMap) throws Exception {
		ModelAndView mav = new ModelAndView();
		BusinessCategory cate = new BusinessCategory();
		cate.setLanguageId(WebUtils.getRequestParameterAsInt(request, "languageId",1));
		cate.setShowType(WebUtils.getRequestParameterAsInt(request, "showType",0));
		cate.setName(WebUtils.getRequestParameterAsString(request, "name"));
		cate.setDesc(WebUtils.getRequestParameterAsString(request, "desc"));
		cate.setOrder(WebUtils.getRequestParameterAsInt(request, "order",0));
		if(cateDao.create(cate)){
			message = "业务领域栏目创建成功!" ;
			UserInfo userInfo = (UserInfo) session.getAttribute(Constants.SESSIONNAME);
			logDao.create(userInfo.getId(),LogConstants.ACTION_INSERT,NavigateConstants.NAVI_BUSINESS,"创建栏目 " + cate.getName());
		}else{
			message = "业务领域栏目创建失败!" ;
		}
		modelMap.put("message", message);
		modelMap.put("href", "super/business/category-list.do");
		mav.setViewName("common/message");
		mav.addAllObjects(modelMap);
		return mav ;
	}
	
	//业务领域--栏目修改
	@RequestMapping(value="/category-update.do")
	public ModelAndView categoryUpdate(HttpServletRequest request,HttpServletResponse response,HttpSession session, ModelMap modelMap) throws Exception {
		ModelAndView mav = new ModelAndView();
		BusinessCategory cate = new BusinessCategory();
		int cateId = WebUtils.getRequestParameterAsInt(request, "cateId", 0);
		cate = cateDao.getBusinessCategory(cateId);
		cate.setLanguageId(WebUtils.getRequestParameterAsInt(request, "languageId",1));
		cate.setShowType(WebUtils.getRequestParameterAsInt(request, "showType",0));
		cate.setName(WebUtils.getRequestParameterAsString(request, "name"));
		cate.setDesc(WebUtils.getRequestParameterAsString(request, "desc"));
		cate.setOrder(WebUtils.getRequestParameterAsInt(request, "order",0));
		if(cateDao.update(cate)){
			message = "业务领域栏目修改成功!" ;
			UserInfo userInfo = (UserInfo) session.getAttribute(Constants.SESSIONNAME);
			logDao.create(userInfo.getId(),LogConstants.ACTION_MODIFY,NavigateConstants.NAVI_BUSINESS,"修改栏目 " + cate.getName());
		}else{
			message = "业务领域栏目修改失败!" ;
		}
		modelMap.put("message", message);
		modelMap.put("href", "super/business/category-list.do");
		mav.setViewName("common/message");
		mav.addAllObjects(modelMap);
		return mav ;
	}
	
	//业务领域--栏目删除
	@RequestMapping(value="/category-del.do")
	public ModelAndView categoryDel(HttpServletRequest request,HttpServletResponse response,HttpSession session, ModelMap modelMap) throws Exception {
		ModelAndView mav = new ModelAndView();
		int cateId = WebUtils.getRequestParameterAsInt(request, "cateId", 0);
		if(cateId > 0){
			BusinessCategory cate = cateDao.getBusinessCategory(cateId);
			if(cateDao.delete(cateId)){
				message = "业务领域栏目删除成功!" ;
				UserInfo userInfo = (UserInfo) session.getAttribute(Constants.SESSIONNAME);
				logDao.create(userInfo.getId(),LogConstants.ACTION_DELETE,NavigateConstants.NAVI_BUSINESS,"删除栏目 " + cate.getName());
			}else{
				message = "业务领域栏目删除失败!" ;
			}
		}
		modelMap.put("message", message);
		modelMap.put("href", "super/business/category-list.do");
		mav.setViewName("common/message");
		mav.addAllObjects(modelMap);
		return mav ;
	}
	
	//业务领域--列举所有的栏目
	@RequestMapping(value="/business-list.do")
	public ModelAndView businessList(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws Exception {
		ModelAndView mav = new ModelAndView();
		int languageId = (String)request.getSession().getAttribute(Constants.SESSIONLANGUAGE) != null ? Integer.parseInt((String)request.getSession().getAttribute(Constants.SESSIONLANGUAGE)) : 1 ;
		List<BusinessCategory> cateList = cateDao.getAll(languageId);
		
		String kw = WebUtils.getRequestParameterAsString(request, "kw");
		kw = StringTools.converISO2UTF8(kw);
		int cateId = WebUtils.getRequestParameterAsInt(request, "cateId", 0);
		int isShowIndex = WebUtils.getRequestParameterAsInt(request, "isShowIndex", -1);
		int isShowList = WebUtils.getRequestParameterAsInt(request, "isShowList", -1);
		int isTop = WebUtils.getRequestParameterAsInt(request, "isTop", -1);
		String startTime = WebUtils.getRequestParameterAsString(request, "startTime");
		String endTime = WebUtils.getRequestParameterAsString(request, "endTime");
		
/*		if(StringUtils.isNotBlank(startTime)){
			startTime = TimeUtils.getDate(new Date(), "yyyy-MM-dd HH:mm:ss", Constants.SEARCH_DAYS);
		}
		if(StringUtils.isNotBlank(endTime)){
			endTime = TimeUtils.getDate(new Date(),"yyyy-MM-dd HH:mm:ss", 0);
		}*/
		BusinessQuery query = new BusinessQuery();
		query.setKw(kw);
		query.setLanguageId(languageId);
		query.setCateId(cateId);
		query.setIsShowIndex(isShowIndex);
		query.setIsShowList(isShowList);
		query.setIsTop(isTop);
		query.setStartTime(startTime);
		query.setEndTime(endTime);
		
	    int curPage = WebUtils.getRequestParameterAsInt(request, "curPage", 1);
	    PageBean pageBean = new PageBean();
	    pageBean.setCurPage(curPage);
	    List<BusinessInfo> businessList = businessDao.getBusinessListByCondition(query, pageBean.getStart(), pageBean.getRowsPerPage());
	    pageBean.setMaxRowCount(businessDao.getBusinessCountByCondition(query));
	    pageBean.setMaxPage();
	    pageBean.setPageNoList();
	    
		modelMap.put("cateList", cateList);
		modelMap.put("businessList", businessList);
		modelMap.put("query", query);
		modelMap.put("pageBean", pageBean);
		mav.setViewName("super/business/business-list");
		mav.addAllObjects(modelMap);
		return mav ;
	}
	
	//业务领域--业务领域新增、修改页面
	@RequestMapping(value="/business-show.do")
	public ModelAndView businessShow(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws Exception {
		ModelAndView mav = new ModelAndView();
		int businessId = WebUtils.getRequestParameterAsInt(request, "businessId", 0);
		int languageId = (String)request.getSession().getAttribute(Constants.SESSIONLANGUAGE) != null ? Integer.parseInt((String)request.getSession().getAttribute(Constants.SESSIONLANGUAGE)) : 1 ;
		List<BusinessCategory> cateList = cateDao.getAll(languageId);
		BusinessInfo business = new BusinessInfo();
		business.setLanguageId(languageId);
		String opt = "create" ;
		if(businessId > 0){
			business = businessDao.getBusinessById(businessId);
			String content = business.getContent();
			business.setContent(ImageContentUtils.setBasePathToImagePath(request, content));
			opt = "update" ;
		}
		modelMap.put("cateList", cateList);
		modelMap.put("opt", opt);
		modelMap.put("business", business);
		modelMap.put("languageId", languageId);
		mav.setViewName("super/business/business-show");
		mav.addAllObjects(modelMap);
		return mav ;
	}
	
	//业务领域--业务领域新增
	@RequestMapping(value="/business-create.do")
	public ModelAndView businessCreate(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("common/message");
		BusinessInfo business = new BusinessInfo();
		String content = WebUtils.getRequestParameterAsString(request, "content") ;
		String textContent = WebUtils.getRequestParameterAsString(request, "textContent");
        int contentType = WebUtils.getRequestParameterAsInt(request, "contentType", 1);
        if ((StringUtils.isBlank(content) && contentType == 1)  || (StringUtils.isBlank(textContent)) && contentType == 0) {
			modelMap.put("message", "内容不能为空!");
			mav.addAllObjects(modelMap);
			return mav ;
		}
		int languageId = WebUtils.getRequestParameterAsInt(request, "languageId",1);
		int cateId = WebUtils.getRequestParameterAsInt(request, "cateId",0);
		
		boolean createFlag = true ;
		//首先判断选定的栏目是否支持列表、详情显示。如果是详情显示的话，需要进行更新操作。
		BusinessInfo dbBusiness = businessDao.isBusinessExist(languageId,cateId);
		if(dbBusiness != null && dbBusiness.getBusinessCategory().getShowType() == 0){
			createFlag = false ;
			business = businessDao.getBusinessById(dbBusiness.getBusinessId());
		}
		
		business.setLanguageId(languageId);
		business.setCateId(cateId);
		business.setTitle(WebUtils.getRequestParameterAsString(request, "title"));
		business.setAuthor(WebUtils.getRequestParameterAsString(request, "title"));
		business.setPublishFrom(WebUtils.getRequestParameterAsString(request, "publishFrom"));
		business.setAuthor(WebUtils.getRequestParameterAsString(request, "author"));
		business.setPublishDate(new java.util.Date());
		business.setMetaKeyword(WebUtils.getRequestParameterAsString(request, "metaKeyword"));
		business.setMetaContent(WebUtils.getRequestParameterAsString(request, "metaContent"));
		business.setSummary(business.getMetaContent());
	
		
		if(contentType == 0 ){
			business.setContent(textContent);
        }
        else{
        	Map<String,String> map = ImageContentUtils.removeImageBasePathForMap(request, content);
        	business.setContent(map.get("content"));
        	business.setFirstImage(map.get("firstImage"));
        }
		business.setContentType(contentType);
		
		if(createFlag){
			if(businessDao.create(business)){
				message = "业务领域创建成功!" ;
				UserInfo userInfo = (UserInfo) request.getSession().getAttribute(Constants.SESSIONNAME);
				logDao.create(userInfo.getId(),LogConstants.ACTION_INSERT,NavigateConstants.NAVI_BUSINESS,"新增内容 " + business.getTitle());
			}else{
				message = "企业创建失败!" ;
			}
		}else{
			if(businessDao.update(business)){
				message = "企业更新成功!" ;
				UserInfo userInfo = (UserInfo) request.getSession().getAttribute(Constants.SESSIONNAME);
				logDao.create(userInfo.getId(),LogConstants.ACTION_MODIFY,NavigateConstants.NAVI_BUSINESS,"修改内容 " + business.getTitle());
			}else{
				message = "企业更新失败!" ;
			}
		}
		modelMap.put("message", message);
		modelMap.put("href", "super/business/business-list.do");
		mav.setViewName("common/message");
		mav.addAllObjects(modelMap);
		return mav ;
	}
	
	//业务领域--业务领域修改
	@RequestMapping(value="/business-update.do")
	public ModelAndView businessUpdate(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws Exception {
		ModelAndView mav = new ModelAndView();
		String content = WebUtils.getRequestParameterAsString(request, "content") ;
		if(StringUtils.isBlank(content)){
			modelMap.put("message", "内容不能为空!");
			mav.addAllObjects(modelMap);
			return mav ;
		}
		
		int businessId = WebUtils.getRequestParameterAsInt(request, "businessId", 0);
		BusinessInfo business = new BusinessInfo();
		business = businessDao.getBusinessById(businessId);
		
		business.setLanguageId(WebUtils.getRequestParameterAsInt(request, "languageId",1));
		business.setCateId(WebUtils.getRequestParameterAsInt(request, "cateId",0));
		business.setTitle(WebUtils.getRequestParameterAsString(request, "title"));
		business.setAuthor(WebUtils.getRequestParameterAsString(request, "title"));
		business.setPublishFrom(WebUtils.getRequestParameterAsString(request, "publishFrom"));
		business.setAuthor(WebUtils.getRequestParameterAsString(request, "author"));
        String publishDate = WebUtils.getRequestParameterAsString(request, "publishDate");
        business.setPublishDate(StringUtils.isBlank(publishDate) ? new java.util.Date() : TimeUtils.formatDate(publishDate));
		business.setMetaKeyword(WebUtils.getRequestParameterAsString(request, "metaKeyword"));
		business.setMetaContent(WebUtils.getRequestParameterAsString(request, "metaContent"));
		business.setSummary(business.getMetaContent());
		
		
		
		Map<String,String> map = ImageContentUtils.removeImageBasePathForMap(request, content);
		business.setContent(map.get("content"));
		business.setFirstImage(map.get("firstImage"));
		
		
		if(businessDao.update(business)){
			message = "业务领域修改成功!" ;
			UserInfo userInfo = (UserInfo) request.getSession().getAttribute(Constants.SESSIONNAME);
			logDao.create(userInfo.getId(),LogConstants.ACTION_MODIFY,NavigateConstants.NAVI_BUSINESS,"修改内容 " + business.getTitle());
		}else{
			message = "业务领域修改失败!" ;
		}
		modelMap.put("message", message);
		modelMap.put("href", "super/business/business-list.do");
		mav.setViewName("common/message");
		mav.addAllObjects(modelMap);
		return mav ;
	}
	
	//业务领域--业务领域删除
	@RequestMapping(value="/business-del.do")
	public ModelAndView businessDel(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws Exception {
		ModelAndView mav = new ModelAndView();
		message = "业务领域删除成功!" ;
		String businessId = WebUtils.getRequestParameterAsString(request, "businessId");
		String ids [] = StringUtils.split(businessId, ",") ;
		boolean flag = false ;
		for(String id : ids){
			BusinessInfo business = businessDao.getBusinessById(Integer.parseInt(id));
			flag = businessDao.delete(Integer.parseInt(id));
			if(flag == false){
				message = "业务领域删除失败!" ;
				break ;
			}
			UserInfo userInfo = (UserInfo) request.getSession().getAttribute(Constants.SESSIONNAME);
			logDao.create(userInfo.getId(),LogConstants.ACTION_DELETE,NavigateConstants.NAVI_BUSINESS,"删除内容 " + business.getTitle());
		}
		modelMap.put("message", message);
		modelMap.put("href", "super/business/business-list.do");
		mav.setViewName("common/message");
		mav.addAllObjects(modelMap);
		return mav ;
	}
	
	//业务领域--首页显示设置
	@RequestMapping(value="/business-setIndex.do")
	public ModelAndView businessSetIndex(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws Exception {
		ModelAndView mav = new ModelAndView();
		String businessId = WebUtils.getRequestParameterAsString(request, "businessId");
		String flag = WebUtils.getRequestParameterAsString(request, "flag");
		if(StringUtils.isNotBlank(flag) && flag.matches("\\d+")){
			String nds [] = StringUtils.split(businessId, ",") ;
			int businessIds [] = new int[nds.length] ;
			int i = 0 ;
			for(String nd : nds){
				businessIds[i] = Integer.valueOf(nd);
				i ++ ;
			}
			if(businessDao.setShowIndex(Integer.valueOf(flag),businessIds)){
				message = "业务领域" + (flag.equals("1") ? "设置首页显示" : "取消首页显示") + "成功!" ;
			}else{
				message = "业务领域" + (flag.equals("1") ? "设置首页显示" : "取消首页显示") + "失败!" ;
			}
		}
		
		modelMap.put("message", message);
		modelMap.put("href", "super/business/business-list.do");
		mav.setViewName("common/message");
		mav.addAllObjects(modelMap);
		return mav ;
	}
	
	//业务领域--列表页显示设置
	@RequestMapping(value="/business-setList.do")
	public ModelAndView businessSetList(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws Exception {
		ModelAndView mav = new ModelAndView();
		String businessId = WebUtils.getRequestParameterAsString(request, "businessId");
		String flag = WebUtils.getRequestParameterAsString(request, "flag");
		if(StringUtils.isNotBlank(flag) && flag.matches("\\d+")){
			String nds [] = StringUtils.split(businessId, ",") ;
			int businessIds [] = new int[nds.length] ;
			int i = 0 ;
			for(String nd : nds){
				businessIds[i] = Integer.valueOf(nd);
				i ++ ;
			}
			if(businessDao.setShowList(Integer.valueOf(flag),businessIds)){
				message = "业务领域" + (flag.equals("1") ? "设置列表页显示" : "取消列表页显示") + "成功!" ;
			}else{
				message = "业务领域" + (flag.equals("1") ? "设置列表页显示" : "取消列表页显示") + "失败!" ;
			}
		}
		
		modelMap.put("message", message);
		modelMap.put("href", "super/business/business-list.do");
		mav.setViewName("common/message");
		mav.addAllObjects(modelMap);
		return mav ;
	}
}